package com.gmail.mariska.martin.server;

import org.apache.log4j.Logger;

import com.gmail.mariska.martin.JPATutorialMain;
import com.gmail.mariska.martin.server.intf.Request;
import com.gmail.mariska.martin.server.intf.Response;
import com.gmail.mariska.martin.server.mockImpl.DefaultRequest;
import com.gmail.mariska.martin.server.mockImpl.DefaultResponse;

public class ServerMain {
	static final Logger logger = Logger.getLogger(ServerMain.class);

	public static void main(String[] args) {
		JPATutorialMain.configureLog4jFromFile();
		new ServerMain().run();
	}

	/**
	 * Main run method
	 * 
	 * @author MAR
	 */
	private void run() {
		Request req = new DefaultRequest();
		req.getParams().put("action", "cz.vera.go");
		Response resp = new DefaultResponse();

		// String actionClass = "com.gmail.mariska.martin.server.TestWebAction";
		String actionClass = "com.gmail.mariska.martin.server.TestWebActionJson";

		IWebActionContainer webAction = getWebActionFromDispacher(actionClass);

		String result = webAction.handle(req, resp);

		logger.info(result);
	}

	/**
	 * Tady by mela byt trida misto funkce pro ziskani action instance MAR
	 * 
	 * @param actionClass
	 *            nazev action tridy
	 * @return instance action tridy
	 */
	private IWebActionContainer getWebActionFromDispacher(String actionClass) {
		IWebActionContainer instance = getInstace(actionClass);

		// add vera bussines rules
		instance = new BussinesWebActionDecorator(instance);
		// instance = new JpaWebActionDecorator(instance);

		return instance;
	}

	private static IWebActionContainer getInstace(String actionClass) {
		try {
			IWebActionContainer instance = null;
			Class<?> forName = Class.forName(actionClass);
			if (!forName.isInstance(IWebActionContainer.class)) {
				logger.info("dispatcher create webAction wrapper.");
				instance = new WebActionInterfaceSwitcherContainer(forName.newInstance());
			} else {
				instance = (IWebActionContainer) forName.newInstance();
			}
			return instance;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		throw new IllegalStateException("Can't create web action");
	}
}
